﻿#ifndef JCONCURRENT_MEDIAN_H
#define JCONCURRENT_MEDIAN_H

#include "jconcurrent_global.h"
#include "tools/jalgorithms.h"
#include <vector>

namespace JConcurrent {

template <typename T>
class Median
{
public:
    Median(int _bufferSize)
        : currentMedian(), bufferSize(_bufferSize), currentIndex(0), valid(false), dirty(true)
    {
        values.resize(bufferSize);
    }

    void reset()
    {
        for (typename jvector<T>::iterator iter = values.begin();
             iter != values.end(); ++iter) {
            *iter = 0;
        }
        currentIndex = 0;
        valid = false;
        dirty = true;
    }

    void addValue(T value)
    {
        currentIndex = ((currentIndex + 1) % bufferSize);
        if (valid == false && currentIndex % bufferSize == 0)
            valid = true;

        // Only update the cached median value when we have to, that
        // is when the new value is on then other side of the median
        // compared to the current value at the index.
        const T currentIndexValue = values[currentIndex];
        if ((currentIndexValue > currentMedian && currentMedian > value)
            || (currentMedian > currentIndexValue && value > currentMedian)) {
            dirty = true;
        }

        values[currentIndex] = value;
    }

    bool isMedianValid() const
    {
        return valid;
    }

    T median()
    {
        if (dirty) {
            dirty = false;
            jvector<T> sorted = values;
            std::sort(sorted.begin(), sorted.end());
            currentMedian = sorted.at(bufferSize / 2 + 1);
        }
        return currentMedian;
    }

private:
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning ( disable: 4251 )
#endif
    jvector<T> values;
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
    T currentMedian;
    int bufferSize;
    int currentIndex;
    bool valid;
    bool dirty;
};

} // namespace JConcurrent

#endif  // JCONCURRENT_MEDIAN_H
